
package com.multimedia.room.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.TextView;

import com.mmclass.libsiren.net.FormFile;
import com.multimedia.room.BaseActivity;
import com.multimedia.room.BaseFragment;
import com.multimedia.room.CommandManager;
import com.multimedia.room.CommonUtil;
import com.multimedia.room.GroupInfo;
import com.multimedia.room.ISwitch;
import com.multimedia.room.IUpdateGroupMembersListenner;
import com.multimedia.room.MediaMessage;
import com.multimedia.room.R;
import com.multimedia.room.SwitchManager;
import com.multimedia.room.urlhttp.CallBackUtil;
import com.multimedia.room.urlhttp.UrlHttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class GroupDiscussFragment extends BaseFragment implements ISwitch, IUpdateGroupMembersListenner{
    private TextView mGroupTitleView, mGroupNumberView, mGroupMemberView,mRecordAlert;
    private MediaMessage mCurrentMessage;
    private String[] mMembers;
    private String mGroupId;
    private View mRootView;
    private String mBasePath;
    private TextView mTeacherView;
    private static final String TAG = GroupDiscussFragment.class.getSimpleName();
    private static final String mAudioPath = "discuss/";
    private static final String mAudioName = "discuss";
    static Handler mHandler = new MsgHandler();
    private static final int MAX_TRY_COUNT = 100;
    private static Object moBjectLock = new Object();
    private static  List<String> sUploadFilesList = new ArrayList<String>();
    private static List<String> sWaitForUploadFilesList = new ArrayList<String>();
    private static String sCurrentFileName = null;
    private static String sLastFileName = null;
    private static final long SPLIT_FILE_TIME = 5*60 * 1000;
    private static int index = 0;
    private static String mFloderPath;
    private static String mUploadUrl = "http://192.168.1.11:8080/API/UploadTalk";
    private static String sWhoesName;
    private SwitchManager mSwitchManager;
    static int uploadTimes = 0;
    boolean issIsRecording = false;

    @Override
    public void switchOn(String params) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startRecording();;
            }
        }, 100);

    }

    @Override
    public void switchOff(String params) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopRecording();
            }
        }, 100);

    }

    @Override
    public void broadcastOn(String params) {

    }

    @Override
    public void brocadOff(String params) {

    }

    static class MsgHandler extends Handler {
        static final int UPLOAD_FILE = 1;
        static final int WHAT_FOR_UPLOAD_PROGRESS = 2;
        static final int SPLIT_RECORD_FILE = 3;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            synchronized (moBjectLock) {
                final String fileName = (String) msg.obj;
                Log.e(TAG, " handleMessage  msg.what = " + msg.what + " UPLOAD_FILE = " + fileName );
                if (UPLOAD_FILE == msg.what) {
                    try {
                        uploadFile(fileName);
                    } catch (Exception e) {
                        Log.e(TAG, " uploadFile failed retry again!", e);
                        Message msg1 = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
                        msg1.obj = fileName;
                        mHandler.sendMessageDelayed(msg1, 1000);
                    }
                } else if (WHAT_FOR_UPLOAD_PROGRESS == msg.what) {
//                    int progress = msg.arg1;
//                    if (circleProgress != null) {
//                        if (circleProgress.getVisibility() != View.VISIBLE) {
//                            circleProgress.setVisibility(View.VISIBLE);
//                        }
//                        circleProgress.setProgress(progress);
//                    }

                } else if (SPLIT_RECORD_FILE == msg.what) {
                    //upload
                    //split
                    Log.i(TAG, "SPLIT_RECORD_FILE");
                    mHandler.post(mSplitRecordRunnable);
                    Message msg1 = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
                    msg1.obj = fileName;
                    mHandler.sendMessageDelayed(msg1, 1000);
                }
            }
        }
    }


    private void checkFileUploadStatus() {
        File fileFloder = new File(mFloderPath);
        if (fileFloder.exists() && fileFloder.isDirectory()) {
            File[] files = fileFloder.listFiles();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    final File file = files[i];
                    Message msg1 = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
                    msg1.obj = file.getName();
                    mHandler.sendMessageDelayed(msg1, 1000);
                    Log.i(TAG, "reupload again for " + file.getName());
                }
            }
        }
    }

    public static GroupDiscussFragment newInstance() {
        GroupDiscussFragment fragment = new GroupDiscussFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.group_layout, null);
        mGroupTitleView = (TextView) mRootView.findViewById(R.id.group_title);
        mGroupNumberView = (TextView) mRootView.findViewById(R.id.group_number);
        mGroupMemberView = (TextView) mRootView.findViewById(R.id.group_member);
        mRecordAlert = (TextView)mRootView.findViewById(R.id.tv_record_alert);
        mRecordAlert.setVisibility(View.GONE);
        mTeacherView = (TextView) mRootView.findViewById(R.id.teacher);
        mTeacherView.setVisibility(View.GONE);
        sWhoesName = checkName(mCurrentMessage.getParams());
        mMembers = mCurrentMessage.getParams().split(",");
        mGroupId = mCurrentMessage.getGroup();
        refresh(mMembers);
        Log.d(TAG, "onCreateView()");
        mBasePath = this.getActivity().getFilesDir().getAbsolutePath();
        mFloderPath = mBasePath + File.separator + mAudioPath;
        mSwitchManager = SwitchManager.getInstance();
        mSwitchManager.registerDiscussSwitch(this);
        checkFileUploadStatus();
        return mRootView;
    }

    private String checkName(String params){
        String paramsStr = params.replace(",","_");
        String own=paramsStr.replace(CommonUtil.getSeatNo()+"_","");
        return CommonUtil.getSeatNo()+own;
    }
    private void refresh(String[] members) {
        if (members == null)
            return;
        String title = members.length + getResources().getString(R.string.group_title);
        mGroupTitleView.setText(title);
        String No = getResources().getString(R.string.group_order) + " " + mGroupId;
        mGroupNumberView.setText(No);
        mTeacherView.setVisibility(View.GONE);
        StringBuilder sb = new StringBuilder();
        for (String mb : members) {
        	if(mb.equals("teacher")){
        		mTeacherView.setVisibility(View.VISIBLE);
        		continue;
        	}
            sb.append(mb).append(" ");
        }
        Log.d("group ", sb.toString());
        String member = getResources().getString(R.string.group_member) + " " + sb.toString();
        mGroupMemberView.setText(member);
        CommandManager.leaveGroup("");
        CommandManager.joinGroup(GroupInfo.getGroupId("g"+mGroupId));

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = this.getArguments();
        if (args != null) {
            mCurrentMessage = (MediaMessage) args.getSerializable("message");
            Log.d("receiver", mCurrentMessage.toString());
        }
        Log.d(TAG, "onCreate");
        implementsIupdate();
    }

    private void implementsIupdate() {
        if (this.getActivity() instanceof BaseActivity) {
            ((BaseActivity) this.getActivity()).registerUpdateGroupMembersListenner(this);
        }
    }

    @Override
    public void joinGroup(String newGroup, String member) {
        Log.d("group", "join group " + newGroup + " " + member);
        if (newGroup != null && newGroup.equals(mGroupId)) {
            List<String> membersList = new ArrayList<String>(Arrays.asList(mMembers));
            if (!membersList.contains(member)) {
                membersList.add(member);
                mMembers = membersList.toArray(new String[membersList.size()]);
                refresh(mMembers);

            }
        }

    }

    @Override
    public void leaveGroup(String member) {
        Log.d("group", "leave group " +" " + member);
        List<String> membersList = new ArrayList<String>(Arrays.asList(mMembers));
        if (membersList.contains(member)) {
            membersList.remove(member);
            mMembers = membersList.toArray(new String[membersList.size()]);
            refresh(mMembers);
        }
    }

    @Override
    public void joinMeGroup(MediaMessage message) {
        Log.d("group", "join me");
        mCurrentMessage = message;
        mMembers = mCurrentMessage.getParams().split(",");
        mGroupId = mCurrentMessage.getGroup();
        refresh(mMembers);

    }
    @Override
	public void onDetach() {
		super.onDetach();
	}

    @Override
    public void onDestroyView() {
        if(!issIsRecording) {
            stopRecording();
        }
        if(mSwitchManager!=null){
            mSwitchManager.unregisterDiscussSwitch(this);
        }
        super.onDestroyView();
    }

    private static boolean uploadFile(String fileName) {

        final File file = new File(mFloderPath, fileName);
        if(!file.exists()){
            Log.d(TAG, "upload file failed due to "+ fileName +" doesn't exits");
            return false;
        }
        CommonUtil.changeMode(mFloderPath);
        CommonUtil.changeMode(file.getAbsolutePath());
        FormFile formfile = new FormFile(fileName, file, "file",
                "application/octet-stream");

        Log.d(TAG,
                "upload start " + mUploadUrl + " === "
                        + fileName
                        + new Date(System.currentTimeMillis())
                        .toString());
        if (file == null) {
//                     Toast.makeText(mContext, "uploadFile failed file is null , return ", Toast.LENGTH_SHORT).show();
            Log.e(TAG, " uploadFile failed file is null , return ");
            return false;
        }


        if (formfile == null) {
//                    Toast.makeText(mContext, "uploadFile failed formfile is null , return", Toast.LENGTH_SHORT).show();

            Log.e(TAG, " uploadFile failed formfile is null , return ");
            return false;
        }

        UrlHttpUtil.uploadFile(mUploadUrl,file, "file", UrlHttpUtil.FILE_TYPE_FILE, new CallBackUtil.CallBackString() {


            @Override
            public void onFailure(int code, String errorMessage) {
                Log.i(TAG, "code " + code + " errorMessage " + errorMessage);
                try {
                    throw new Exception("uploadFile failed");
                } catch (Exception e) {
                    Log.e(TAG, "uploadFile failed ", e);
                }
            }

            @Override
            public void onResponse(String response) {
                Log.i(TAG, "onResponse " + response);
                try {
                    JSONObject rootJson = new JSONObject(response);
                    if(rootJson!=null&&rootJson.has("Code")){
                        int code = rootJson.getInt("Code");
                        if(0 == code){
                            Log.i(TAG, "upload successful " + file.getName());
                            File tmp = new File(mFloderPath + File.separator + file.getName());
                            if(tmp.isFile()){
                                tmp.delete();
                                Log.i(TAG, "upload successful delete local file" + file.getName());
                            }
                        }else{
                            try {
                                throw new Exception("uploadFile failed");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        sWaitForUploadFilesList.remove(fileName);
        CommandManager.sendUpdateCompletionMessage();
        return true;


    }


    private void startRecording() {
        mRecordAlert.setVisibility(View.VISIBLE);
        Log.d(TAG, "startRecording");
//        CommandManager.openMic();
        sIsRecording = true;
        final String fileName =  sWhoesName + "_" + mAudioName  + "_" + System.currentTimeMillis()
                + ".mp3";
        sLastFileName = fileName;
        File floder = new File(mFloderPath);
        File file = new File(mFloderPath + File.separator + fileName);
        if (floder.exists()) {
            // Nothing to do
        } else {
            floder.mkdirs();
        }
        try {
            CommandManager.startRecord(file.getAbsolutePath());
            Message msg = mHandler.obtainMessage(MsgHandler.SPLIT_RECORD_FILE);
            msg.obj = fileName;
            mHandler.sendMessageDelayed(msg, SPLIT_FILE_TIME);
        } catch (Throwable t) {
            Log.e("AudioRecord", "Recording Failed");
        }
        uploadTimes = 0;
    }

    private static Runnable mSplitRecordRunnable = new Runnable() {
        @Override
        public void run() {
            splitRecord();
        }
    };

    private static void splitRecord() {

        if (sIsRecording) {


            final String fileName = sWhoesName + "_" + mAudioName + "_" + System.currentTimeMillis()
                    + ".mp3";

            sLastFileName = fileName;
            Log.i(TAG, "splitRecord : " + fileName);
            File floder = new File(mFloderPath);
            File file = new File(mFloderPath + File.separator + fileName);
            if (floder.exists()) {
                // Nothing to do
            } else {
                floder.mkdirs();
            }
            // 删除录音文件
            if (file.exists())
                file.delete();
            CommandManager.splitRecord(file.getAbsolutePath());
            Message msg = mHandler.obtainMessage(MsgHandler.SPLIT_RECORD_FILE);
            msg.obj = fileName;
            mHandler.sendMessageDelayed(msg, SPLIT_FILE_TIME);
        }
    }

    // 音频获取源
    public static boolean sIsRecording = false;
    private void stopRecording() {
        mRecordAlert.setVisibility(View.GONE);
        sIsRecording = false;
        try {
            CommandManager.stopRecord();
            // mRecorder.stopRecording();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.d(TAG, "record over");
        if(!TextUtils.isEmpty(sLastFileName)){
            Message msg = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
            msg.obj=sLastFileName;
            mHandler.sendMessageDelayed(msg,1000);
        }
        mHandler.removeMessages(MsgHandler.SPLIT_RECORD_FILE);


    }


}
